package com.web.exiaodao.remote.controller;

import com.web.exiaodao.business.constant.JConstant;
import com.web.exiaodao.business.entity.ShopCar;
import com.web.exiaodao.business.entity.ShopStandardName;
import com.web.exiaodao.business.repository.ShopStandardNameRepository;
import com.web.exiaodao.remote.service.ApiShopCarService;
import com.web.exiaodao.remote.service.ApiShopService;
import com.web.exiaodao.remote.service.ApiShopStandardValuesService;
import com.web.exiaodao.remote.service.ApiUserService;
import com.web.exiaodao.remote.vo.ShopCarVo;
import com.web.exiaodao.remote.vo.ShopVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.controller.BaseController;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.result.XaResult;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author zhanglin
 * @version V1.0
 * @Title: ApiShopCarController.java
 * @Package com.web.exiaodao.remote.controller
 * @Description: 商品-购物车信息接口
 * @date 2016-11-02 18:25:27
 */
@Api(value = "ShopCar", description = "购物车接口", position = 10)
@Controller
@RequestMapping("/api/shopCar")
public class ApiShopCarController extends BaseController {

    private static final Logger LOGGER = Logger.getLogger(ApiShopCarController.class);

    @Autowired
    private ApiShopCarService shopCarService;

    @Autowired
    private ApiUserService userService;

    @Autowired
    private ApiShopService shopService;

    @Autowired
    private ApiShopStandardValuesService standardValuesService;

    @Autowired
    private ShopStandardNameRepository shopStandardNameRepository;

    /**
     * @return
     * @Title: save
     * @Description: 新增一条实体
     */
    @ApiOperation(value = "加入购物车", notes = "加入购物车,当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value = "addShopCar", method = RequestMethod.POST)
    public XaResult<ShopCarVo> addShopCar(
            @ApiParam("用户Id,字段名:userId") @RequestParam(value = "userId") Long userId,
            @ApiParam("商品的id,字段名:shopId") @RequestParam(value = "shopId") Long shopId,
            @ApiParam("数量,字段名:shopNumber") @RequestParam(value = "shopNumber", defaultValue = "1") Long shopNumber,
            @ApiParam("规格Id,字段名:standardIds;多个规格值,用逗号分割,如:1,22,45说明:规格值id1,规格值id22,规格值id45") @RequestParam(value = "standardIds", required = false) String standardIds,
            HttpServletRequest request
    ) throws BusinessException {
        XaResult<ShopCarVo> xr = new XaResult<ShopCarVo>();
        if (XaUtil.isEmpty(userId)) {
            xr.error("用户Id不能为空！");
            return xr;
        }
        if (XaUtil.isEmpty(shopNumber)) {
            xr.error("数量不能为空！");
            return xr;
        }
        if (shopNumber < 1) {
            xr.error("数量必须大于0");
            return xr;
        }
        if (XaUtil.isEmpty(standardIds)) {
            xr.error("商品必须要有规格!");
            return xr;
        }
        List<String> standardList = null;
        try {
            //逗号替换
            standardIds = standardIds.replace(JConstant.SYMBOL_DOT_CN, JConstant.SYMBOL_DOT).trim();
            standardList = Arrays.asList(standardIds.split(JConstant.SYMBOL_DOT));
            Collections.sort(standardList, new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    if (Long.parseLong(o1) > Long.parseLong(o2)) {
                        return -1;
                    } else if (Long.parseLong(o1) < Long.parseLong(o2)) {
                        return 1;
                    }
                    throw new RuntimeException();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            xr.error("购物车商品规格格式错误!");
            LOGGER.error(XaConstant.Message.error, new Throwable(e));
            return xr;
        }
        //排序
        try {
            //校验数据
            userService.findOne(userId);
            ShopVo shopVo = shopService.findOne(shopId).getObject();
            HashSet<Long> nameIds = new HashSet<>();
            for (int i = 0; i < standardList.size(); ++i) {
                nameIds.add(standardValuesService.findOne(Long.parseLong(standardList.get(i))).getObject().getShopStandsNameId());
            }
            List<ShopStandardName> names = shopStandardNameRepository.findByShopIdAndStatusNot(shopId, XaConstant.Status.delete);
            if (nameIds.size() != standardList.size() ||  names.size() != standardList.size()) {
                xr.error("购物车商品规格有误,应该有规格:" + names.size() + "个");
                return xr;
            }
            if (shopVo.getShopProductInventory().longValue() < shopNumber.longValue()) {
                xr.error("库存不足");
                return xr;
            }
            ShopCar model = new ShopCar();
            model.setShopId(shopId);
            model.setCarNumber(shopNumber);
            model.setUserId(userId);
            model.setStandardIds(standardIds);

            return shopCarService.addCar(model);
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                xr.error(e.getMessage());
            } else {
                xr.error(XaConstant.Message.error);
            }
            LOGGER.error(XaConstant.Message.error, new Throwable(e));
        }
        return xr;
    }

    /**
     * @return
     * @Title:
     * @Description: 修改购物车
     */
    @ApiOperation(value = "修改购物车", notes = "修改购物车(只能修改数量),当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value = "updateShopCar", method = RequestMethod.POST)
    public XaResult<List<ShopCarVo>> updateShopCar(
            @ApiParam("购物车实体，json格式的字符串格式：[{\"id\":1,\"carNumber\":2},{\"id\":2,\"carNumber\":3}]") @RequestParam(value = "shopCar") String shopCar
    ) throws BusinessException {
        XaResult<List<ShopCarVo>> xr = new XaResult<List<ShopCarVo>>();
        if (XaUtil.isEmpty(shopCar)) {
            xr.error("购物车实体不能为空!", true);
            return xr;
        }
        try {
            xr = shopCarService.modifyCar(shopCar);
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                xr.error(e.getMessage());
            } else {
                xr.error(XaConstant.Message.error);
            }
            LOGGER.error(XaConstant.Message.error, new Throwable(e));
        }
        return xr;
    }

    /**
     * @param userId
     * @param ids
     * @return
     * @Title:
     * @Description: 删除购物车
     */
    @ApiOperation(value = "删除购物车", notes = "删除购物车,当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value = "deleteShopCars", method = RequestMethod.POST)
    public XaResult<ShopCarVo> deleteShopCars(
            @ApiParam("购物车id,字段名:ids (购物车id,用逗号分割开)") @RequestParam(value = "ids") String ids,
            @ApiParam("用户Id,字段名:userId") @RequestParam(value = "userId") Long userId,
            HttpServletRequest request
    ) throws BusinessException {
        XaResult<ShopCarVo> xr = new XaResult<ShopCarVo>();
        if (XaUtil.isEmpty(ids)) {
            xr.error("购物车id不能为空!");
            return xr;
        }
        ids = ids.replace(JConstant.SYMBOL_DOT_CN, JConstant.SYMBOL_DOT);
        if (XaUtil.isEmpty(userId)) {
            xr.error("用户Id不能为空!");
            return xr;
        }
        try {
            return shopCarService.deleteCar(ids, userId);
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                xr.error(e.getMessage());
            } else {
                xr.error(XaConstant.Message.error);
            }
            LOGGER.error(XaConstant.Message.error, new Throwable(e));
        }
        return xr;
    }


    /**
     * @return
     * @Title: findShopCars
     * @Description: 购物车列表
     */
    @ApiOperation(value = "购物车列表", notes = "购物车列表,当返回的code=1时，取出object进行显示,存放为数组对象")
    @ResponseBody
    @RequestMapping(value = "findShopCars", method = RequestMethod.POST)
    public XaResult<Page<ShopCarVo>> findShopCars(
            @ApiParam("用户Id,字段名:userId") @RequestParam(value = "userId") Long userId,
            @ApiParam("页号,字段名:nextPage,默认0,从第0页开始") @RequestParam(defaultValue = "0") Integer nextPage,
            @ApiParam("页长,字段名:pageSize,默认10") @RequestParam(defaultValue = "10") Integer pageSize
    ) throws BusinessException {
        XaResult<Page<ShopCarVo>> xr = new XaResult<>();
        if (XaUtil.isEmpty(userId)) {
            xr.error("用户Id不能为空！");
            return xr;
        }
        return shopCarService.findMyCar(userId, nextPage, pageSize);
    }

    /**
     * @return
     * @Title: findShopCarsCount
     * @Description: 购物车数量
     */
    @ApiOperation(value = "购物车数量", notes = "购物车数量,当返回的code=1时，取出object进行显示,存放为数组对象")
    @ResponseBody
    @RequestMapping(value = "findShopCarsCount", method = RequestMethod.POST)
    public XaResult<Long> findShopCarsCount(
            @ApiParam("用户Id,字段名:userId") @RequestParam(value = "userId") Long userId
    ) throws BusinessException {
        XaResult<Long> xr = new XaResult<>();
        if (XaUtil.isEmpty(userId)) {
            xr.error("用户Id不能为空！");
            return xr;
        }
        return shopCarService.findMyCarCount(userId);
    }
}

